<template>
  <!-- 导航栏 -->
  <van-nav-bar
    title="确认订单"
    left-text="返回"
    left-arrow
    fixed
    placeholder
    z-index="1000"
    @click-left="back"
  />

  <!-- 收货地址 -->
  <van-contact-card v-if="address" type="edit" :name="`${address.name} ${address.region_text}`" :tel="address.tel" @click="AddressSelect" />
  <van-contact-card v-else type="add" @click="AddressAdd" add-text="添加地址" />


  <!-- 商品卡片 -->
  <van-card
    v-for="item in list"
    :key="item.id"
    :thumb="item.product.thumbs_text"
    :num="item.nums"
    @click-thumb="toProductInfo(item.proid)"
  >
  
    <template #title>
      <div class="title">{{item.product.name}}</div>
    </template>

    <!-- 商品规格 -->
    <template #desc v-if="item.prop_list.length">
      <div class="TagGroup">
        <van-tag v-for="(attr,index) in item.prop_list" :key="index" class="tag" type="primary">{{attr}}</van-tag>
      </div>
    </template>
    <template #desc v-else>
      <div class="TagGroup">
        <van-tag class="tag" type="danger">无规格数据</van-tag>
      </div>
    </template>

    <template #tags>
      <div class="price">单价：￥{{item.price}}</div>
    </template>

    <template #price>
      <div class="price">合计：￥{{item.total}}</div>
    </template>
  </van-card>


  <!-- 支付方式 -->
  <van-cell title="支付方式" :value="PayActive.text" is-link @click="PayShow = true"></van-cell>

  <!-- 优惠券 -->
  <van-coupon-cell
    :coupons="CouponList"
    :chosen-coupon="CouponActive"
    @click="CouponShow = true"
  />

  <!-- 订单备注 -->
  <van-field
    v-model="remark"
    rows="2"
    autosize
    label="订单备注"
    type="textarea"
    maxlength="120"
    placeholder="请输入订单备注"
    show-word-limit
  />

  <!-- 优惠券选择器 -->
  <van-popup 
    v-model:show="CouponShow" 
    position="bottom"
    style="height: 90%; padding-top: 4px;"
  >
    <van-coupon-list
      :coupons="CouponList"
      :chosen-coupon="CouponActive"
      :exchange-button-disabled="true"
      :show-exchange-bar="false"
      @change="CouponSelect"
    />
  </van-popup>

  <!-- 支付方式的选择器 -->
  <van-popup v-model:show="PayShow" position="bottom">
    <van-picker
      title="选择支付方式"
      :columns="PayList"
      @cancel="PayShow = false"
      @confirm="PayConfirm"
    />
  </van-popup>

  <!-- 提交动作栏 -->
  <van-submit-bar text-align="left" :price="total" button-text="确认支付" @submit="submit" />
</template>

<script setup>
import { onBeforeMount } from "vue"


  const {proxy} = getCurrentInstance()
  let business = proxy.$business

  const type = proxy.$route.query.type??''

  //获取下单的购物车id
  let cartids = proxy.$route.query.cartids ? proxy.$route.query.cartids : '0'
  let list = ref([]) //购物车数据
  let address = ref(null) //收货地址
  let remark = ref('') //订单备注
 
  //支付方式
  let PayShow = ref(false)
  let PayActive = ref({text: '余额支付', value: 'money'})
  let PayList = ref([
    {text: '余额支付', value: 'money'},
    {text: '微信支付', value: 'wx'},
    {text: '支付宝', value: 'zfb'},
  ])

  // 优惠券
  const CouponList = ref([]);
  let CouponShow = ref(false);
  let CouponActive = ref(-1);
  onBeforeMount(()=>{
    if(type=='live')
    {
      liveProductInfo()
    }else{
      CartInfo()
    }
    AddressInfo()
    CouponInfo()
  })
  const initTotal = ref(0)
  const liveProductInfo = async(params)=>{
    let result = await proxy.$GET({
      url:"/live/product",
      params:proxy.$route.query
    })
    list.value = result
    if(!list.value.length){
      showFailToast({
        message: '购买的商品不能为空',
        duration: 1000,
        onClose:proxy.$router.push('/cart')
      })
    }
    initTotal.value = result[0].total*100
  }
  const CartInfo = async()=>{
    let result = await proxy.$GET({
      url:"/product/cart",
      params:{status:"1"}
    })
    list.value = result
    if(!list.value.length){
      showFailToast({
        message: '购买的商品不能为空',
        duration: 1000,
        onClose:proxy.$router.push('/cart')
      })
    }
    initTotal.value = result.reduce((pre,cur)=>{
      return pre+parseFloat(cur.total)
    },0)*100
  }

  const AddressInfo = async()=>{
    let result = await proxy.$GET({
      url:"/business/address"
    })
    if(!result.length)return
    let addressRow = null;
    let addressid = proxy.$route.query.addressid
    let ad = result.filter(a=>a.id==addressid)
    if(ad.length){
      addressRow = ad[0]
    }else{
      ad = result.filter(a=>a.status=='1')
      addressRow = ad.length?ad[0]:result[0]
    }
    address.value = {
      id:addressRow.id,
      name:addressRow.consignee,
      region_text:addressRow.province_text+addressRow.city_text+addressRow.district_text+addressRow.address,
      tel:addressRow.mobile
    }
  }
  const CouponInfo = async()=>{
    let result = await proxy.$GET({
      url:"/coupon/received",
    })
    result.forEach(coupon => {
      let c = {
        id:coupon.id,
        available: 1,
        condition: '无门槛',
        reason: '',
        value: initTotal.value*(1-parseFloat(coupon.rate)),
        name: coupon.title,
        startAt: coupon.createtime,
        endAt: coupon.endtime,
        valueDesc: coupon.rate*100%10?coupon.rate*100:coupon.rate*10,
        unitDesc: '折',
      }
      CouponList.value.push(c)
    });
  }
  const CouponSelect = (index) => {
    CouponShow.value = false;
    CouponActive.value = index;
    // console.log(CouponActive.value)
  };
  // 总价合计
  const total = computed(() =>  CouponActive.value!=-1?initTotal.value-CouponList.value[CouponActive.value].value:initTotal.value)

  //确认支付方式
  const PayConfirm = async ({selectedOptions}) => 
  {
    PayShow.value = false
    PayActive.value = selectedOptions[0]
  }


  //跳转收货地址的列表界面
  const AddressSelect = () => 
  {
    proxy.$router.push({path: '/address', query: {action: 'select',addressid:address.value.id}})
  }

  //跳转收货地址添加界面
  const AddressAdd = () => proxy.$router.push({path: '/address/add', query: {action: 'select'}})

  //返回上一页
  const back = () => proxy.$router.go(-1)

  //提交订单
  const submit = async()=>{
    let result = {}
    if(type!='live')
    {
      result = await proxy.$POST({  
        url:'/order',
        data:{
          businessaddrid:address.value.id,
          remark:remark.value,
          couponid:CouponList.value[CouponActive.value]?CouponList.value[CouponActive.value].id:0,
          pay:PayActive.value.value
        }
      })
    }else{
      let query = proxy.$route.query
      result = await proxy.$POST({  
        url:'/live/order',
        data:{
          ...query,
          businessaddrid:address.value.id,
          remark:remark.value,
          couponid:CouponList.value[CouponActive.value]?CouponList.value[CouponActive.value].id:0,
          pay:PayActive.value.value
        }
      })
    }
    
    if(result.code==1){
      showSuccessToast({
        message: result.msg,
        duration: 1000,
        onClose:proxy.$router.push('/order')
      })
    }else if(result.code==-1){
      if(type!='live')
      {
        proxy.$router.push({path:'/cart/cashier',query:{payid:result.data}})
      }else{
        let query = proxy.$route.query
        proxy.$router.push({path:'/cart/cashier',query:{payid:result.data,...query}})
      }
    }else{
      showFailToast({
        message: result.msg,
        duration: 1000,
      })
    }
  }

</script>

<style scoped>
  :deep(.cart) {
    display: flex;
    width: 100%;
  }
  ::v-deep .van-swipe-cell {
    width: 100%;
  }
  .delete-button {
    height: 100%;
  }


  .van-card{
    background-color:#fff;
  }

  .title{
    font-size:16px;
    font-weight: bold;
    margin-bottom:5px;
  }

  .TagGroup{
    margin-bottom:5px;
  }

  .tag{
    margin-right:5px;
  }

  .price{
    font-size:14px;
    font-weight: bold;
  }
</style>